<template>
  <ContainerGroup>
    <Container style="margin-bottom:10px;">
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        @submit="handleSearch"
        @reset="handlerReset"
      />
    </Container>
    <Container height="fill" display="flexY">
      <OperationContainer class="operation-box">
        <!-- <Button icon="reset" :loading="cjLoading" @click="handleCollection">采集用友数据</Button> -->
        <!-- <span>最近采集时间：2023-01-03 00:00:00</span> -->
        <div class="opt-right">
          <Button type="info" icon="cloudy" :loading="xzmbLoading" @click="handleExport(0)">下载模板</Button>
          <el-upload
            ref="upload"
            style="display:inline-block;"
            :show-file-list="false"
            :on-change="handlechange"
            class="upload-demo"
            action
            :auto-upload="false"
          >
            <el-button :loading="drLoading" class="btn-import el-icon-upload2">导入</el-button>
          </el-upload>
          <Button type="info" :loading="dcLoading" icon="export" @click="handleExport(1)">导出</Button>
        </div>
      </OperationContainer>
      <Table
        :columns="tableColumns"
        :loading="tableLoading"
        :data="tableData"
        :pagination="{
          total: total,
          current: currentPage,
          pageSize: pageSize,
        }"
        @paginationChange="pageChange"
      >
        <template #caozuo="{ row }">
          <Tooltip content="编辑" icon="edit" @click="handleEidt(row)" />
          <Tooltip v-if="row.id" content="删除" icon="delete" @click="handleDelete(row)" />
        </template>
      </Table>
      <!-- 新增、编辑 -->
      <Drawer
        :title="title"
        :visible="isShow"
        :header-color="'#e7ecf8'"
        :loading="confirmLoading"
        width="500px"
        :footer-btns="[
          {
            text: '确定',
            type: 'primary',
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="isShow = false"
        @submit="handleSubmit"
      >
        <el-form
          v-if="isShow"
          ref="ruleForm"
          size="mini"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="科目编码" prop="accountCode">
            <el-input v-model.trim="ruleForm.accountCode" placeholder="请输入科目编码" disabled />
          </el-form-item>
          <el-form-item label="科目名称" prop="accountName">
            <el-input v-model.trim="ruleForm.accountName" placeholder="请输入科目名称" disabled />
          </el-form-item>
          <el-form-item label="项目类别">
            <el-select
              v-model="ruleForm.projectTypeCode"
              placeholder="请选择项目类别"
              filterable
              clear
              style="width:100%;"
            >
              <el-option
                v-for="item in filterElements[2].options"
                :key="item.entryCode"
                :label="item.entryName"
                :value="item.entryCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="费用类别" prop="expenseTypeCode">
            <el-select
              v-model="ruleForm.expenseTypeCode"
              placeholder="请选择费用类别"
              filterable
              clear
              style="width:100%;"
            >
              <el-option
                v-for="item in filterElements[3].options"
                :key="item.entryCode"
                :label="item.entryName"
                :value="item.entryCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="收支类型" prop="reExTypeCode">
            <el-select
              v-model="ruleForm.reExTypeCode"
              placeholder="请选择收支类型"
              filterable
              clear
              style="width:100%;"
            >
              <el-option
                v-for="item in filterElements[4].options"
                :key="item.entryCode"
                :label="item.entryName"
                :value="item.entryCode"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </Drawer>
    </Container>
  </ContainerGroup>
</template>
<script>
import {
  zxExpenseTypePage,
  zxExpenseDelete,
  getEntryByDictId,
  zxExpenseDownload,
  zxExpenseTypeSaveFile,
  zxExpenseTypeSaveOrUpdate
} from '@/apis/specialFunds/systermSetting'
export default {
  name: 'ExpenseCategory', // 费用类别
  data() {
    return {
      confirmLoading: false,
      title: '编辑费用类别',
      isShow: false,
      xmlbList: [],
      fyList: [],
      szlxList: [],
      ruleForm: {
        accountCode: '',
        accountName: '',
        expenseTypeCode: '',
        projectTypeCode: '',
        reExTypeCode: ''
      },
      rules: {
        accountCode: [
          { required: true, message: '请输入科目编码', trigger: 'blur' }
        ],
        accountName: [
          { required: true, message: '请输入科目名称', trigger: 'blur' }
        ],
        projectTypeCode: [
          { required: true, message: '请选择项目类别', trigger: 'change' }
        ],
        expenseTypeCode: [
          { required: true, message: '请选择费用类别', trigger: 'change' }
        ],
        reExTypeCode: [
          { required: true, message: '请选择收支类型', trigger: 'change' }
        ]
      },
      xzmbLoading: false,
      dcLoading: false,
      drLoading: false,
      cjLoading: false,
      filterElements: [
        {
          key: 'accountCode',
          type: 'input',
          label: '科目编码',
          value: ''
        },
        {
          key: 'accountName',
          type: 'input',
          label: '科目名称',
          value: ''
        },
        {
          key: 'projectTypeCode',
          type: 'Select',
          label: '项目类别',
          value: '',
          itemLabel: 'entryName',
          itemValue: 'entryCode',
          options: [],
          filterable: true,
          clearable: true
        },
        {
          key: 'expenseTypeCode',
          type: 'Select',
          label: '费用类别',
          value: '',
          itemLabel: 'entryName',
          itemValue: 'entryCode',
          options: [],
          filterable: true,
          clearable: true
        },
        {
          key: 'reExTypeCode',
          type: 'Select',
          label: '收支类型',
          value: '',
          itemLabel: 'entryName',
          itemValue: 'entryCode',
          options: [],
          filterable: true,
          clearable: true
        }
      ],
      tableColumns: [
        {
          title: '科目编码',
          dataIndex: 'accountCode'
        },
        {
          title: '科目名称',
          dataIndex: 'accountName'
        },
        {
          title: '项目类别',
          dataIndex: 'projectTypeName'
        },
        {
          title: '费用类别',
          dataIndex: 'expenseTypeName'
        },
        {
          title: '收支类型',
          dataIndex: 'reExTypeName'
        },
        {
          title: '创建时间',
          dataIndex: 'createtime'
        },
        {
          title: '操作',
          width: 160,
          type: 'otherTag',
          dataIndex: 'caozuo'
        }
      ],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableLoading: false,
      tableData: [],
      newCondition: {},
      rowObj: null
    }
  },
  created() {
    this.getSelect(2, 1001) // 项目类别
    this.getSelect(3, 1002) // 费用类别
    this.getSelect(4, 1003) // 收支类型
  },
  methods: {
    getSelect(type, code) {
      getEntryByDictId(code).then(res => {
        if (res.data.code === 200) {
          this.filterElements[type].options = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleSubmit() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          const param = {
            accountCode: this.ruleForm.accountCode,
            accountName: this.ruleForm.accountName,
            expenseTypeCode: this.ruleForm.expenseTypeCode,
            expenseTypeName: this.filterElements[3].options.find(
              item => item.entryCode === this.ruleForm.expenseTypeCode
            )?.entryName,
            projectTypeCode: this.ruleForm.projectTypeCode,
            projectTypeName: this.filterElements[2].options.find(
              item => item.entryCode === this.ruleForm.projectTypeCode
            )?.entryName,
            reExTypeCode: this.ruleForm.reExTypeCode,
            reExTypeName: this.filterElements[4].options.find(
              item => item.entryCode === this.ruleForm.reExTypeCode
            )?.entryName,
            id: this.rowObj?.id
          }
          this.confirmLoading = true
          zxExpenseTypeSaveOrUpdate(param).then(res => {
            this.confirmLoading = false
            this.isShow = false
            if (res.data.code === 200) {
              this.getData()
              this.handleClear()
              this.$message.success(res.data.message)
            } else {
              this.$message.error(res.data.message)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleClear() {
      for (const key in this.ruleForm) {
        this.ruleForm[key] = ''
      }
    },
    handlechange(file, fileList) {
      // 导入
      const fileType = file.name.substr(file.name.lastIndexOf('.')).trim()
      if (fileType !== '.xlsx' && fileType !== '.xls') {
        this.$message.warning('请选择Excel格式的文件导入！')
        return
      }
      const files = file.raw
      const formData = new FormData()
      formData.append('file', files)
      const param = {
        formData: formData
      }
      zxExpenseTypeSaveFile(param).then(res => {
        this.drLoading = false
        if (res.data.code === 200) {
          this.$message.success('上传成功')
          this.getData()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleExport(type) {
      // 导出
      const param = {
        entity: {
          accountCode: this.$refs.filterForm.getParms()?.accountCode || '',
          accountName: this.$refs.filterForm.getParms()?.accountName || '',
          expenseTypeCode:
            this.$refs.filterForm.getParms()?.expenseTypeCode || '',
          projectTypeCode:
            this.$refs.filterForm.getParms()?.projectTypeCode || '',
          reExTypeCode: this.$refs.filterForm.getParms()?.reExTypeCode || ''
        },
        isMuBan: type // 0表示下载模版，1表示下载文件
      }
      if (type === 0) {
        this.xzmbLoading = true
      } else {
        this.dcLoading = true
      }
      zxExpenseDownload(param).then(res => {
        if (type === 0) {
          this.xzmbLoading = false
        } else {
          this.dcLoading = false
        }
        const blob = new Blob([res.data], {
          type: res.data.type + 'charset=utf-8'
        })
        const downloadLink = document.createElement('a')
        const URL = window.URL || window.webkitURL || window.moxURL
        const downUrl = URL.createObjectURL(blob)
        downloadLink.href = downUrl
        downloadLink.download = '科目关系对照.xlsx'
        downloadLink.click()
        window.URL.revokeObjectURL(downUrl)
        // document.body.removeChild(downloadLink) // 删除 a 标签
      })
    },
    handleCollection() {
      // 采集数据
      this.cjLoading = true
    },
    handleEidt(row) {
      // 编辑
      this.rowObj = row
      this.isShow = true
      this.setDetails(this.rowObj)
    },
    setDetails(row) {
      for (const key in this.ruleForm) {
        if (row[key]) {
          this.ruleForm[key] = row[key] + ''
        }
      }
    },
    handleDelete(row) {
      this.$confirm({
        content: '此操作将删除该条记录，并无法恢复， 是否继续?',
        title: '温馨提示',
        okFn: res => {
          zxExpenseDelete({ id: row.id }).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getData()
            }
          })
        },
        cancelFn: res => {
          console.log('取消')
        }
      })
    },
    handleSearch(value) {
      this.newCondition = value
      this.currentPage = 1
      this.getData(value)
    },
    getData() {
      const params = {
        accountCode: this.newCondition?.accountCode,
        accountName: this.newCondition?.accountName,
        expenseTypeCode: this.newCondition?.expenseTypeCode,
        projectTypeCode: this.newCondition?.projectTypeCode,
        reExTypeCode: this.newCondition?.reExTypeCode,
        pageNo: this.currentPage,
        pageSize: this.pageSize
      }
      this.tableLoading = true
      zxExpenseTypePage(params)
        .then(res => {
          this.tableLoading = false
          if (res.data.code === 200) {
            this.tableData = res.data.data.list
            this.total = res.data.data.total
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch(() => {
          this.tableLoading = false
        })
    },
    handlerReset(val) {
      this.handleSearch()
    },
    pageChange(payload) {
      this.currentPage = payload.current
      this.pageSize = payload.pageSize
      this.getData()
    }
  }
}
</script>
<style lang="less" scoped>
.operation-box {
  margin-bottom: 10px;
}
.opt-right {
  display: flex;
  flex: 1;
  justify-content: flex-end;
}
.btn-import {
  height: 30px;
  display: flex;
  align-items: center;
  margin: 0px 10px;
  &:hover {
    background: white;
    color: #333;
    border: 1px solid #dedede;
  }
}
.demo-ruleForm {
  padding: 15px 10px;
  box-sizing: border-box;
}
</style>
